<!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>手写路由</title>
  </head>
  <body>
    <h3>手动实现一个简单路由</h3>
    <div id="app"></div>
    <script src="/node_modules/vue/dist/vue.global.js"></script>
    <script>
        (function(){

            const Home = {
                template: `<div>Home</div>`
            }

            const About = {
                template: `<div>About</div>`
            }

            const NotFound = {
                template: `<div>Not Found</div>`
            }

            const routes = {
                '/': Home,
                '/about': About
            }

            const App = {
                template: `<div>
                                <a href="#/">Home</a> |
                                <a href="#/about">About</a> |
                                <a href="#/non-existent-path">Broken Link</a>
                            </div>
                            <component :is="currentView"></component>`,
                data() {
                    return {
                        currentPath: window.location.hash
                    }
                },
                computed: {
                    currentView(){
                    let path = this.currentPath.slice(1) || '/'
                    return routes[ path ] || NotFound;
                    }
                },
                mounted() {
                    // 监听地址栏中的 hash 更改事件 (hashchange)
                    window.addEventListener('hashchange', () => {
                        this.currentPath = window.location.hash;
                    });
                }
            }

            const app = Vue.createApp(App);
            app.mount('#app');
        })();
    </script>
  </body>
</html>
